package com.xxl.job.executor.utils;

import com.alibaba.druid.proxy.jdbc.ClobProxyImpl;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.xxl.job.core.util.DateUtil;
import dm.jdbc.driver.DmdbClob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.*;

/**
 * 业务工具类
 *
 * @Author: liyazhou
 * @CreateDate: 2018/11/6 10:41
 **/
public class BusinessUtils {
    private static Logger logger = LoggerFactory.getLogger(BusinessUtils.class);
    /**
     * 获取属性类型(type)，属性名(name)，属性值(value)的map组成的list
     * */
    public static List getFiledsInfo(Object o){
        Field[] fields=o.getClass().getDeclaredFields();
        String[] fieldNames=new String[fields.length];
        List list = new ArrayList();
        Map infoMap=null;
        for(int i=0;i<fields.length;i++){
            infoMap = new HashMap();
            infoMap.put("type", fields[i].getType().toString());
            infoMap.put("name", fields[i].getName());
            infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
            list.add(infoMap);
        }
        return list;
    }

    /**
     * 根据属性名获取属性值
     * */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }


    /**
     * 获取属性名数组
     * */
    public static String[] getFiledName(Object o){
        Field[] fields=o.getClass().getDeclaredFields();
        String[] fieldNames=new String[fields.length];
        for(int i=0;i<fields.length;i++){
            System.out.println(fields[i].getType());
            fieldNames[i]=fields[i].getName();
        }
        return fieldNames;
    }


    /**
     * 获取对象的所有属性值，返回一个对象数组
     * */
    public static Object[] getFiledValues(Object o){
        String[] fieldNames=getFiledName(o);
        Object[] value=new Object[fieldNames.length];
        for(int i=0;i<fieldNames.length;i++){
            value[i]=getFieldValueByName(fieldNames[i], o);
        }
        return value;
    }

    /**
     * 获取单个查询记录sql
     *
     *      格式：where column1='2018-12-23 00:00:00' and column2=1 and column3='admin3'...;
     *
     * @author      liyazhou
     * @param map
     * @date        2018/11/23 17:41
     **/
    public static String getSelectVlues(Map<String, Object> map) {
        String and = "";
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();

            Object object = map.get(key);
            if (null!=object){
                if (object instanceof String ){
                    if(!StringUtils.isEmpty(object)){
                        and+=" and "+key+"='"+object+"'";
                    }
                }else{
                    and+=" and "+key+"="+object;
                }
            }
        }
        and = " where "+and.substring(4);
        return and;
    }

    /**
     * 获取单个插入记录sql
     *
     *      格式：(column1,column2,column3,...) values ('2018-12-23 00:00:00',1,'admin3',...);
     *
     * @author      liyazhou
     * @param map
     * @date        2018/11/23 17:41
     **/
    public static String getInsertVlues(Map<String, Object> map) {
        String column = "";
        String value = "";
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            column+=","+key;
            Object object = map.get(key);
            value += ","+(null==object?"null":object instanceof String?"'"+object+"'":object+"");
        }
        String columns = "("+column.substring(1,column.length())+")";
        String values = "("+value.substring(1,value.length())+")";
        String sql = columns+" values"+values+";";
        return sql;
    }

    /**
     * 获取批量插入的列与值的sql
     *
     * insert into ZFW_WW_DC.T_ACE_MOCK (CREATE_AT,CREATE_BY,NAME,AGE,SEX)
     values ('2018-12-23 00:00:00',1,'admin2',20,'0'),('2018-12-23 00:00:00',1,'admin3',20,null);
     * @param list
     */
    public static String getBatchSQL(List<Map<String, Object>> list){
        String sql = "";
        if (!CollectionUtils.isEmpty(list)) {
            //组合列名集合
            String columns = "";
            //TODO-考虑最多列的map
            Map<String,Object> map = list.get(0);
            List<String> keys = Lists.newArrayList();
            String column = "";
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                keys.add(key);
                column+=","+key;
            }
            columns = "("+column.substring(1,column.length())+")";

            //组合值的集合
            String values = "";
            for (Map<String, Object> obj :list) {
                String value = "";
                for (String key : keys) {
                    Object object = obj.get(key);
                    value += ","+(null==object?"null":object instanceof String?"'"+object+"'":object+"");
                }
                value = "("+value.substring(1,value.length())+")";
                values += ","+value;
            }
            values = values.substring(1,values.length());
            sql = columns+" values "+values+";";
        }
        return sql;
    }



    /**
     * 获取达梦数据库大字段的值
     *
     * @param row
     */
    public static void setTextVal(Map<String, Object> row) {
        if (null==row || row.isEmpty()){
            return;
        }
        for (Map.Entry<String, Object> entry : row.entrySet()) {
            if (entry.getValue() instanceof ClobProxyImpl || entry.getValue() instanceof DmdbClob){
                String value = null;
                try {
                    DmdbClob dbClob = (DmdbClob) entry.getValue();
                    value = dbClob.getSubString(1, (int) dbClob.length());
                } catch (Exception e) {
                    logger.warn("达梦大字段DmdbClob取值异常："+Throwables.getStackTraceAsString(e));
                    try {
                        ClobProxyImpl dmdbClob = (ClobProxyImpl) entry.getValue();
                        value = dmdbClob.getSubString(1, (int) dmdbClob.length());
                    } catch (SQLException se) {
                        logger.warn("达梦大字段ClobProxyImpl取值异常："+Throwables.getStackTraceAsString(se));
                    }
                }
                row.put(entry.getKey(),value);
            }
        }
    }

    /**
     * 获取单个修改的sql
     *
     *  update T_ACE_MOCK set CREATE_AT='2018-12-23 00:00:00',CREATE_BY=1,NAME='admin',AGE=20,SEX='1'
     *
     * @param map
     * @return
     */
    public static String getUpdateSQLWithWwxh(Map<String,Object> map) {
        String set = null;
        if (null==map){
            return set;
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(",");
            String key = entry.getKey();
            sb.append(key+"=");
            Object object = map.get(key);
            sb.append(null==object?"null":object instanceof String?"'"+object+"'":object+"");
        }
        if (sb.length()>1){
            set = sb.substring(1);
        }
        return set;
    }
}
